//
//  CYLTabBarControllerConfig.m
//  CYLTabBarController
//
//  v1.13.1 Created by 微博@iOS程序犭袁 ( http://weibo.com/luohanchenyilong/ ) on 10/20/15.
//  Copyright © 2015 https://github.com/ChenYilong . All rights reserved.
//
#import "CYLTabBarControllerConfig.h"

static CGFloat const CYLTabBarControllerHeight = 36.f;




#import "CollectionViewController.h"
#import "PersonalViewController.h"
#import "MainPageViewController.h"
#import "SpecialViewController.h"

@interface CYLTabBarControllerConfig ()<UITabBarControllerDelegate>

@property (nonatomic, readwrite, strong) CYLTabBarController *tabBarController;


@end

@implementation CYLTabBarControllerConfig

/**
 *  lazy load tabBarController
 *
 *  @return CYLTabBarController
 */
- (CYLTabBarController *)tabBarController {
    if (_tabBarController == nil) {
        /**
         * 以下两行代码目的在于手动设置让TabBarItem只显示图标，不显示文字，并让图标垂直居中。
         * 等效于在 `-tabBarItemsAttributesForController` 方法中不传 `CYLTabBarItemTitle` 字段。
         * 更推荐后一种做法。
         */
//        UIEdgeInsets imageInsets = UIEdgeInsetsMake(0, 0, 0, 0);//UIEdgeInsetsMake(4.5, 0, -4.5, 0);
//        UIOffset titlePositionAdjustment = UIOffsetMake(0, -4);;//UIOffsetMake(0, MAXFLOAT);
        UIEdgeInsets imageInsets ;
        if (CYL_IS_IPHONE_X) {
            imageInsets = UIEdgeInsetsMake(14, 0, -14, 0);//UIEdgeInsetsMake(4.5, 0, -4.5, 0);
        }else{
            imageInsets = UIEdgeInsetsMake(2, 0, -2, 0);//UIEdgeInsetsMake(4.5, 0, -4.5, 0);
        }
        
        UIOffset titlePositionAdjustment;
        if (CYL_IS_IPHONE_X) {
            titlePositionAdjustment = UIOffsetMake(0, 20);//UIOffsetMake(0, MAXFLOAT);
        }else{
            titlePositionAdjustment = UIOffsetMake(0, -2);//UIOffsetMake(0, MAXFLOAT);
        }
        
        
        CYLTabBarController *tabBarController = [CYLTabBarController tabBarControllerWithViewControllers:self.viewControllers
                                                                                   tabBarItemsAttributes:self.tabBarItemsAttributesForController
                                                 imageInsets:imageInsets titlePositionAdjustment:titlePositionAdjustment];
        
        
        [self customizeTabBarAppearance:tabBarController];
        _tabBarController = tabBarController;
        
        
    }
    return _tabBarController;
}

- (NSArray *)viewControllers {
    MainPageViewController *vc1 = [MainPageViewController new];
    SpecialViewController *vc2 = [SpecialViewController new];
    PersonalViewController *vc3 = [PersonalViewController new];

    BaseNavigationController *nav1 = [[BaseNavigationController alloc] initWithRootViewController:vc1];
    BaseNavigationController *nav2 = [[BaseNavigationController alloc] initWithRootViewController:vc2];
    BaseNavigationController *nav3 = [[BaseNavigationController alloc] initWithRootViewController:vc3];

    NSArray *viewControllers = @[
                                 nav1,
                                 nav2,
                                 nav3
                                 ];
    return viewControllers;
}
- (NSArray *)tabBarItemsAttributesForController {
    //    tabTheme21_h
    
    NSDictionary *firstTabBarItemsAttributes = @{
                                                 CYLTabBarItemTitle : @"首页",
                                                 CYLTabBarItemImage : @"tab1",
                                                 CYLTabBarItemSelectedImage : @"tab1_h",
                                                 };
    NSDictionary *secondTabBarItemsAttributes = @{
                                                  CYLTabBarItemTitle : @"特价",
                                                  CYLTabBarItemImage : @"tab2",
                                                  CYLTabBarItemSelectedImage : @"tab2_h",
                                                  };
    
    NSDictionary *thirdTabBarItemsAttributes = @{
                                                 CYLTabBarItemTitle : @"我的",
                                                 CYLTabBarItemImage : @"tab3",
                                                 CYLTabBarItemSelectedImage : @"tab3_h",
                                                 };
    
    NSArray *tabBarItemsAttributes = @[
                                       firstTabBarItemsAttributes,
                                       secondTabBarItemsAttributes,
                                       thirdTabBarItemsAttributes,
                                       ];
    
    return tabBarItemsAttributes;
}
/**
 *  更多TabBar自定义设置：比如：tabBarItem 的选中和不选中文字和背景图片属性、tabbar 背景图片属性等等
 */
- (void)customizeTabBarAppearance:(CYLTabBarController *)tabBarController {
#warning CUSTOMIZE YOUR TABBAR APPEARANCE
    // Customize UITabBar height
    // 自定义 TabBar 高度
//     tabBarController.tabBarHeight = 46;
    tabBarController.tabBarHeight = CYL_IS_IPHONE_X ? 65 : 48;
    
    // set the text color for unselected state
    // 普通状态下的文字属性
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];

        normalAttrs[NSForegroundColorAttributeName] = [UIColor colorWithHexString:@"#989898" andAlpha:1];

    
    normalAttrs[NSFontAttributeName] = [UIFont boldSystemFontOfSize:10];
    // set the text color for selected state
    // 选中状态下的文字属性
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = THEMECOLOR;
 
    
    selectedAttrs[NSFontAttributeName] = [UIFont boldSystemFontOfSize:10];
    
    
    // set the text Attributes
    // 设置文字属性
    UITabBarItem *tabBar = [UITabBarItem appearance];
    [tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
    [tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
}

- (void)updateTabBarCustomizationWhenTabBarItemWidthDidUpdate {
    void (^deviceOrientationDidChangeBlock)(NSNotification *) = ^(NSNotification *notification) {
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
        if ((orientation == UIDeviceOrientationLandscapeLeft) || (orientation == UIDeviceOrientationLandscapeRight)) {
            NSLog(@"Landscape Left or Right !");
        } else if (orientation == UIDeviceOrientationPortrait) {
            NSLog(@"Landscape portrait!");
        }
        [self customizeTabBarSelectionIndicatorImage];
    };
    [[NSNotificationCenter defaultCenter] addObserverForName:CYLTabBarItemWidthDidChangeNotification
                                                      object:nil
                                                       queue:[NSOperationQueue mainQueue]
                                                  usingBlock:deviceOrientationDidChangeBlock];
}

- (void)customizeTabBarSelectionIndicatorImage {
    ///Get initialized TabBar Height if exists, otherwise get Default TabBar Height.
    CGFloat tabBarHeight = CYLTabBarControllerHeight;
    CGSize selectionIndicatorImageSize = CGSizeMake(CYLTabBarItemWidth, tabBarHeight);
    //Get initialized TabBar if exists.
    UITabBar *tabBar = [self cyl_tabBarController].tabBar ?: [UITabBar appearance];
    [tabBar setSelectionIndicatorImage:
     [[self class] imageWithColor:[UIColor yellowColor]
                             size:selectionIndicatorImageSize]];
}

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width + 1, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
    
}

+ (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize {
    CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width * scaleSize, image.size.height * scaleSize);
    UIGraphicsBeginImageContextWithOptions(size, NO, 1.0);
    [image drawInRect:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}


@end
